package org.brakepedal.server.support.controller.responseBodyAdvice;

import org.brakepedal.server.support.http.ComResponseBody;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * Date: 2023/2/12 0:47
 * 有bug(可能不是我的不过),controller不能直接传String, 会报 字符串转换异常
 * */
//@RestControllerAdvice(basePackages = "com.pdl.chatroomjava.controller")
public class SetDefaultResponseAdvice  implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(@NotNull MethodParameter returnType, @NotNull Class converterType) {
        // 从ioc容器中取出 PageResponseBodyAdvice 实例, 若PageResponseBodyAdvice 可以处理则 ComResponseBodyAdvice 不处理
        return  Objects.requireNonNull(returnType.getMethod()).getReturnType() == String.class;
    }

    @Override
    public Object beforeBodyWrite(Object body, @NotNull MethodParameter returnType,
                                  @NotNull MediaType selectedContentType, @NotNull Class selectedConverterType,
                                  @NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response) {
        if(body == null || ComResponseBody.SUCCESS.getMsg().equals(body)) {
            return ComResponseBody.SUCCESS;
        } else if(ComResponseBody.WARN.getMsg().equals(body)) {
            return ComResponseBody.WARN;
        } else if (ComResponseBody.ERROR.getMsg().equals(body)) {
            return ComResponseBody.ERROR;
        }

        return body;
    }
}
